﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LastfmNet.Models
{
    public class LastfmOpenSearch<T> : LastfmPager<T> where T : LastfmModelBase, new()
    {
        public LastfmOpenSearch()
        {
            this.QueryRole = string.Empty;
            this.SearchTerms = string.Empty;
            this.StartIndex = 0;
            this.Page = 0;
            this.PerPage = 0;
            this.TotalPages = 0;
            this.Total = 0;
            this.ItemsList = new List<T>();
        }

        public LastfmOpenSearch(XmlNode node, string matchesNodeName)
        {
            if (node == null) return;
            this.InitializeFromXmlNode(node, matchesNodeName);
        }

        public override void InitializeFromXmlNode(XmlNode node)
        {
            throw new NotSupportedException("InitializeFromXmlNode with one parameter is not supported for LastfmOpenSearch. Use InitializeFromXmlNode(XmlNode node, string matchesNodeName) instead.");
        }

        public void InitializeFromXmlNode(XmlNode node, string matchesNodeName)
        {
            if (node == null) return;
            this.QueryRole = node.GetChild("opensearch:Query").GetAttributeValue("role");
            this.SearchTerms = node.GetChild("opensearch:Query").GetAttributeValue("searchTerms");
            this.StartIndex = node.GetChildValue("opensearch:startIndex").ToInteger();
            this.Page = node.GetChild("opensearch:Query").GetAttributeValue("startPage").ToInteger();
            this.PerPage = node.GetChildValue("opensearch:itemsPerPage").ToInteger();
            this.Total = node.GetChildValue("opensearch:totalResults").ToInteger();
            if (this.PerPage <= 0)
            {
                this.TotalPages = 0;
            }
            else
            {
                this.TotalPages = (int)Math.Ceiling((double)this.Total / (double)this.PerPage);
            }
            this.ItemsList = LastfmModelBase.GetList<T>(node.GetChild(matchesNodeName), null);
        }

        public string QueryRole
        {
            get;
            set;
        }

        public string SearchTerms
        {
            get;
            set;
        }

        public int StartIndex
        {
            get;
            set;
        }
    }
}
